var express = require('express')
var router = express.Router()
var db = require('../config/db.config');
/**
 * 获取所有信息
 */
router.get('/getAll', (req, res) => {
  db.query('select * from message order by m_id desc', (err, data) => {
    if (err) {
      res.send({ code: 0, msg: "error", data: [] })
    } else {
      res.send({ code: 200, msg: "success", data })
    }
  })
})
/**
 * 添加信息
 * @param {String} data
 * @param {String} content
 */
router.post('/add', (req, res) => {
  const data = req.body.data
  const content = req.body.content
  db.query(`insert into message (data, content) values('${data}','${content}')`, (err, data) => {
    if (err) {
      res.send({ code: 0, msg: err.message })
    } else {
      res.send({ code: 200, msg: "success", data: { msg: 'success' } })
    }
  })
})
/**
 * 修改消息
 * @param {integer} id
 * @param {string} content
 */
router.patch('/update/:id', (req, res) => {
  res.send(req.params.id)
  console.log("更新操作执行成功")
})
router.patch('/updateOne', (req, res) => {
  const id = req.body.id
  const content = req.body.content
  if (!id && !content) {
    res.send({ code: 0, msg: "缺少字段，无法进行更新操作" })
    return
  }
  db.query(`update message set content = '${content}' where m_id = ${id}`, (err, data) => {
    if (err) {
      res.send({ code: 0, msg: err.message })
    } else {
      res.send({ code: 200, msg: "success" })
    }
  })
})
/**
 * 单个删除信息
 *  @param {integer} id
 */
router.delete('/delete', (req, res) => {
  const id = req.body.id
  console.log(id)
  if (!id) {
    res.send({ code: 0, msg: "缺失必要参数，无法进行删除操作" })
    return
  }
  db.query(`delete from message where m_id = ${id}`, (err, data) => {
    if (err) {
      res.send({
        code: 0,
        msg: err,
        data: { msg: 'error' }
      })
    } else {
      res.send({
        code: 200,
        msg: "success",
        data: { msg: 'success' }
      })
    }
  })
})
/**
 * 批量删除
 * @param {Array} ids
 */
router.delete('/deleteMore', (req, res) => {
  const ids = req.body.ids
  console.log(req.body.ids)
  let promises = []
  for (let i = 0; i < ids.length; i++) {
    let promise = new Promise((resolve, reject) => {
      db.query(`delete from message where m_id = ${ids[i]}`, (err, data) => {
        if (err) {
          console.log(err)
          reject(err)
        }
        else {
          resolve(data)
        }
      })
    })
    promises.push(promise)
  }
  Promise.all(promises).then(() => {
    res.send({
      code: 200,
      msg: 'success',
      data: { msg: "success" }
    })
  }).catch(err => {
    res.send({
      code: 0,
      msg: err,
      data: { msg: 'error' }
    })
  })
})
module.exports = router